import { login } from '@/api/user'
import { setToken, getToken, removeToken, setTimeStamp } from '@/utils/auth'
import { Message } from 'element-ui'
// import { resetRouter } from '@/router'

const getDefaultState = () => {
  return {
    token: getToken() || null,
    name: '',
    avatar: '',
    articleId: null
  }
}

const state = getDefaultState()

const mutations = {

  setToken(state, token) {
    state.token = token
    setToken(token)
  },
  removeToken(state, token) {
    state.token = null
    removeToken()
  }
}

const actions = {
  // user login
  async login(state, data) {
    try {
      const res = await login(data)
      console.log(res)
      console.log(res.token)
      state.commit('setToken', res.token)
      // 存到本地
      console.log(res.token)
      setTimeStamp()
    } catch (e) {
      Message.error('验证码错误')
    }

    // console.log(res.data.data.token)
    // 把token存到本地 和vuex
  },

  //  点击退出
  logout(state, payload) {
    state.commit('removeToken', {})
    removeToken()
  },

  // remove token
  resetToken({ commit }) {
    return new Promise((resolve) => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
